<?php
defined('IN_APP') or die('Access Denied');
class TaomeeFucker
{
    private $request_file;
    private $local_file;
    function __construct() {
        $i = stripos($_SERVER['REQUEST_URI'], '?');
        if ($i){
            $request = substr($_SERVER['REQUEST_URI'], 0, $i);
        }else{
            $request = $_SERVER['REQUEST_URI'];
        }
        $this->request_file = $request;
        $this->local_file = DOCROOT.$request;
        if ($request == '/')
            $this->local_file .= 'index.html';
    }
    public function run()
    {
        if (file_exists($this->local_file))
        {
            $data = $this->local();
        }else{
            $data = $this->forward();
        }
        output($data);
    }
    public function local()
    {
        global $_config;
        $data['time'] = time();
        $data['status'] = 200;
        $data['body'] = file_get_contents($this->local_file);
        $finfo = new finfo(FILEINFO_MIME); 
        $data['mime'] = $finfo->file($this->local_file);
        $data['from'] = 'origin'; //暂时不支持缓存到cache
        $data['source'] = 'local';
        return $data;
    }
    public function forward()
    {
        try{
            global $_config;
            $memc = new gateway_memcached($_config['memcached']['host'], intval($_config['memcached']['port']) );
            function update_cache($memc, $key)
            {
                global $_config;
                $source_url = $_config['source']['baseurl'].$key;
                $expiration = $_config['memcached']['expiration'];
                $data = $memc->update($key, $source_url, $expiration);
                return $data;
            }
            $data = $memc->get($this->request_file, 'update_cache');
            $data['source'] = 'remote';
            return($data);
        }
        catch(Source_Excpetion $e)
        {
            echo "<b>Source_Excpetion:</b> ", $e->getText(), "<br/>\n";
            throw $e;
        }
        catch(Memcached_Excpetion $e)
        {
            echo "<b>Memcached_Excpetion:</b> ", $e->getText(), "<br/>\n";
            throw $e;
        }
    }
}
